const api = require("@/api/api").api;
import VODUpload from './aliyun-upload-sdk-1.0.1.min.js'

export default {
	uploader: null,
	videoSize:1000,
	init(config={}) {

		this.uploader = new VODUpload({
			timeout: config.timeout || 60000,
			region: config.region || "cn-beijing",
			// 添加文件成功
			addFileSuccess: (uploadInfo) => {
				console.log("addFileSuccess" ,uploadInfo)
				if(typeof config.addFileSuccess=='function'){
					config.addFileSuccess({uploadInfo});
				}
			},
			// 开始上传
			onUploadstarted: (uploadInfo) =>{
				console.log('文件开始上传...');
				console.log("onUploadStarted:",uploadInfo)

				var url;
				// if (uploadInfo.isImage) {
				// 	url =
				// 		"https://alivc-demo.aliyuncs.com/demo/getImageUploadAuth?imageType=default&imageExt=" +
				// 		that._getSuffix(uploadInfo.url) + "&title=title&tags=tags";
				// } else {
				// 	url = "https://alivc-demo.aliyuncs.com/demo/getVideoUploadAuth?title=" + uploadInfo
				// 		.url + "&fileName=" + uploadInfo.url + "&fileSize=" + uploadInfo.fileSize +
				// 		"&description=description&coverURL=" + uploadInfo.coverUrl + "&tags=tags";
				// }

				api.base.ossGetVideoToken({
					coverURL: uploadInfo.coverUrl,
					tags: config.tags?config.tags:getApp().globalData.shareTitle,
					description: config.description?config.description:"乡野生活分享家视频",
					fileSize:uploadInfo.fileSize ? uploadInfo.fileSize: this.videoSize ,
					fileName:uploadInfo.url,
					title: config.title?config.title:uploadInfo.url

				}).then(res => {
					console.log(res,"res.datares.datares.data")
					var akInfo = res.data;
					this.uploader.setUploadAuthAndAddress(uploadInfo, akInfo.uploadAuth,
						akInfo.uploadAddress, akInfo.videoId);
				}).catch((res)=>{
					console.log(res)
					this.uploader.stopUpload();
				})

 

			},
			// 文件上传成功
			onUploadSucceed:  (uploadInfo)  =>{
				console.log(uploadInfo)
				console.log('文件上传成功!')
				if(typeof config.onUploadSucceed=='function'){
					config.onUploadSucceed(uploadInfo);
				}
				
			},
			// 文件上传失败
			onUploadFailed:  (uploadInfo, code, message) => {
				console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code +
					", message:" + message)
				console.log('文件上传失败!')
				this.uploader.stopUpload();
			},
			// 取消文件上传
			onUploadCanceled:  (uploadInfo, code, message) => {
				console.log(JSON.stringify(uploadInfo) + code + message)
				console.log('文件已暂停上传!')
				this.uploader.stopUpload();

			},
			// 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
			onUploadProgress:  (uploadInfo, totalSize, progress)  =>{
				// console.log(JSON.stringify(uploadInfo) + "|" + totalSize + "|" + progress)
				// console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(progress * 100) + "%")
				// var progressPercent = Math.ceil(progress * 100)
				// console.log('文件上传中...' + progressPercent);
				// $('#sts-progress').text(progressPercent)
				// $('#status').text('文件上传中...')

				let progressPercent = 0;
				if(progress<90){
					progressPercent = progress;
				}else{
					progressPercent = 90 +   parseInt(( (progress-90) * 0.9).toFixed(2));
				}

				if(typeof config.onUploadProgress=="function"){
					config.onUploadProgress({
						uploadInfo,totalSize,progress:progressPercent
					})
				}
				

				//todo 
				// files.forEach((file, idx) => {
				// 	if (file.url === uploadInfo.url) {
				// 		file.progress = progress;
				// 		if (uploadInfo.isImage) {
				// 			that.setData({
				// 				images: files
				// 			})
				// 		} else {
				// 			that.setData({
				// 				videos: files
				// 			})
				// 		}
				// 	}
				// })


				

			},
			// 上传凭证超时
			onUploadTokenExpired:  (uploadInfo)  =>{
				// // 如果是上传方式二即根据 STSToken 实现时，从新获取STS临时账号用于恢复上传
				// // 上传文件过大时可能在上传过程中 sts token 就会失效, 所以需要在 token 过期的回调中调用 resumeUploadWithSTSToken 方法
				// // 这里是测试接口, 所以我直接获取了 STSToken
				// $('#status').text('文件上传超时!')
				//
				// var stsUrl = 'http://demo-vod.cn-shanghai.aliyuncs.com/voddemo/CreateSecurityToken?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=67999yyuuuy&AppVersion=1.0.0'
				// $.get(stsUrl, function (data) {
				//     var info = data.SecurityTokenInfo
				//     var accessKeyId = info.AccessKeyId
				//     var accessKeySecret = info.AccessKeySecret
				//     var secretToken = info.SecurityToken
				//     var expiration = info.Expiration
				//     uploader.resumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken, expiration)
				// }, 'json')
			},
			// 全部文件上传结束
			onUploadEnd:  (uploadInfo) => {
				uni.showToast({
					title: '上传成功',
					icon: 'success',
					duration: 2000
				})
				console.log("文件上传完毕 onUploadEnd: uploaded all the files",uploadInfo);
				 
				if(typeof config.onUploadEnd=='function'){
					config.onUploadEnd({uploadInfo});
				}
			}
		});

	}
}
